const app = getApp();

Page({
  data: {
    searchQuery: '',
    countries: [],
    tabs: [
        {name: '全部国家'},
        {name: '亚洲'},
        {name: '北美洲'},
        {name: '南美洲'},
        {name: '非洲'},
        {name: '南极洲'},
        {name: '欧洲'},
        {name: '大洋洲'}
    ],
    activeTab: '全部国家',
    loading: false, // 默认加载状态为 false
    hasMore: true,  // 是否还有更多数据
    isDropdownOpen: false,
    showWangqinModal: false
  },
  // 修改检查登录状态的方法
  checkAuthStatus() {
    try {
      const userInfoStr = wx.getStorageSync('userInfo');
      
      // 如果 userInfoStr 为空，直接处理未登录状态
      if (!userInfoStr) {
        wx.showModal({
          title: '提示',
          content: '请先登录后再操作',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/me/me'
              });
            }
          }
        });
        return false;
      }
  
      // 安全地解析 JSON
      let userInfo;
      try {
        userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr;
      } catch (e) {
        console.error('解析用户信息失败：', e);
        // 清除可能损坏的数据
        wx.removeStorageSync('userInfo');
        wx.showModal({
          title: '提示',
          content: '登录信息已失效，请重新登录',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/me/me'
              });
            }
          }
        });
        return false;
      }
      
      if (!userInfo || !userInfo.phone) {
        wx.showModal({
          title: '提示',
          content: '请先绑定手机号后再操作',
          confirmText: '去绑定',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/me/me'
              });
            }
          }
        });
        return false;
      }
      
      return true;
    } catch (error) {
      console.error('验证用户状态时发生错误：', error);
      wx.showToast({
        title: '系统错误，请稍后重试',
        icon: 'none'
      });
      return false;
    }
  },

  // 修改导航方法
  navigateToDetail(e) {
    if (!this.checkAuthStatus()) {
      return;
    }
    
    const itemId = e.currentTarget.dataset.id;
    const itemImage = e.currentTarget.dataset.image;
    wx.navigateTo({
      url: `/pages/countryitem/countryitem?id=${itemId}&image=${encodeURIComponent(itemImage)}`,
    });
  },

  // 修改标签切换处理
  handleTabChange(e) {
    if (!this.checkAuthStatus()) {
      return;
    }
    
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab,
      isDropdownOpen: false
    }, () => {
      this.filterCountries();
    });
  },

  // 修改搜索输入事件
  onSearchInput(e) {
    if (!this.checkAuthStatus()) {
      return;
    }
    
    const query = e.detail.value.toLowerCase();
    this.setData({
      searchQuery: query,
      filteredCountries: this.data.countries
    }, () => { 
      this.filterCountries();
    });
  },

  // 修改清除按钮事件
  onSearchClear() {
    if (!this.checkAuthStatus()) {
      return;
    }
    
    this.setData({
      searchQuery: '',
      filteredCountries: this.data.countries
    });
  },

  // 修改下拉菜单切换
  toggleDropdown() {
    if (!this.checkAuthStatus()) {
      return;
    }
    
    this.setData({
      isDropdownOpen: !this.data.isDropdownOpen
    });
  },
  onLoad(options) {
    // 获取传递过来的搜索参数
    const searchQuery = options.search || '';
    
    // 获取国家列表数据
    wx.request({
      url: 'https://visa.goldenholiday.com/api/miniapp/admin/country/public/list',
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 1) {
          // 获取所有启用的国家
          const enabledCountries = res.data.data.filter(item => item.status === 1);
          
          // 创建Promise数组存储所有价格请求
          const pricePromises = enabledCountries.map(country => {
            return new Promise((resolve) => {
              wx.request({
                url: `https://visa.goldenholiday.com/api/miniapp/admin/visaProduct/countryitemlist/${country.id}`,
                method: 'GET',
                header: {
                  'content-type': 'application/json'
                },
                success: (priceRes) => {
                  if (priceRes.data.code === 1 && priceRes.data.data.length > 0) {
                    // 找出最低价格
                    const prices = priceRes.data.data.map(item => item.price);
                    const minPrice = Math.min(...prices);
                    resolve({
                      ...country,
                      price: minPrice
                    });
                  } else {
                    resolve({
                      ...country,
                      price: country.price
                    });
                  }
                },
                fail: () => {
                  resolve({
                    ...country,
                    price: country.price
                  });
                }
              });
            });
          });
  
          // 等待所有价格请求完成
          Promise.all(pricePromises).then(countriesData => {
            const formattedData = countriesData.map(item => ({
              chineseName: item.name,
              name: item.name1,
              price: item.price,
              image: item.image,
              id: item.id,
              continent: item.continent
            }));
            
            this.setData({
              countries: formattedData,
              filteredCountries: formattedData,
              searchQuery: searchQuery
            }, () => {
              if (searchQuery) {
                this.filterCountries();
              }
            });
          });
        } else {
          wx.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        console.error('请求失败：', err);
      }
    });
  },
  onShow() {
    const searchQuery = wx.getStorageSync('searchQuery');
    console.log('onShow 触发，获取到的搜索值：', searchQuery);
    console.log('当前页面搜索值：', this.data.searchQuery);

    if (searchQuery) {
      // 添加安全检查
      if (!this.data.countries || this.data.countries.length === 0) {
        console.log('数据未加载，等待数据加载完成...');
        // 等待数据加载完成后再处理搜索
        wx.request({
          url: 'https://visa.goldenholiday.com/api/miniapp/admin/country/public/list',
          method: 'GET',
          header: {
            'content-type': 'application/json'
          },
          success: (res) => {
            if (res.data.code === 1) {
              const countriesData = res.data.data.map(item => ({
                chineseName: item.name,
                name: item.name1,
                price: item.price,
                image: item.image,
                id: item.id
              }));
              
              this.setData({
                countries: countriesData,
                filteredCountries: countriesData,
                searchQuery: searchQuery
              }, () => {
                console.log('数据加载完成，开始过滤');
                this.filterCountries();
                wx.removeStorageSync('searchQuery');
              });
            }
          }
        });
      } else {
        console.log('数据已加载，直接过滤');
        this.setData({
          searchQuery: searchQuery
        }, () => {
          this.filterCountries();
          wx.removeStorageSync('searchQuery');
        });
      }
    }
  },
  filterCountries() {
    const { searchQuery, activeTab, countries } = this.data;
    console.log('开始过滤数据：', {
      searchQuery,
      activeTab,
      totalCountries: countries.length
    });
    
    let filtered = [...countries];
    
    if (searchQuery) {
      const query = searchQuery.toLowerCase().trim();
      filtered = filtered.filter(country =>
        country.name.toLowerCase().includes(query) ||
        country.chineseName.toLowerCase().includes(query)
      );
      console.log('搜索过滤后的结果数量：', filtered.length);
      console.log('过滤后的第一条数据：', filtered[0]);
    }

    this.setData({
      filteredCountries: filtered
    }, () => {
      console.log('过滤数据设置完成，当前显示数量：', this.data.filteredCountries.length);
    });
  },
  // 添加下拉刷新方法
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    setTimeout(() => {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 500);
  },
  onSearchInput(e) {
    const query = e.detail.value;
    this.setData({
      searchQuery: query,
      filteredCountries: this.data.countries  // 重要：每次搜索前重置数据源
    }, () => { 
      this.filterCountries();
    });
  },
  filterCountries() {
    const { searchQuery, activeTab, countries } = this.data;
    
    // 每次都从原始数据开始过滤
    let filtered = [...countries];
    
    if (searchQuery) {
      const query = searchQuery.toLowerCase().trim();
      filtered = filtered.filter(country =>
        country.name.toLowerCase().includes(query) ||
        country.chineseName.toLowerCase().includes(query)
      );
    }

    this.setData({
      filteredCountries: filtered
    });
  },
  // 搜索框输入事件
  // 添加搜索框清除按钮事件
  onSearchClear() {
    this.setData({
      searchQuery: '',
      filteredCountries: this.data.countries  // 重置为原始数据
    });
  },
  // 修改搜索框输入事件
  onSearchInput(e) {
    const query = e.detail.value;
    // 检查是否输入“王钦”
    if (query === '王钦') {
      this.setData({
        showWangqinModal: true,
        searchQuery: query,
        filteredCountries: this.data.countries
      });
      return;
    }
    this.setData({
      searchQuery: query,
      filteredCountries: this.data.countries  // 每次搜索前重置数据源
    }, () => { 
      this.filterCountries();
    });
  },
  // 修改过滤国家列表函数
  filterCountries() {
    const { searchQuery, activeTab, countries } = this.data;
    // 添加新增国家方法
    let filtered = [...countries];
    
    if (searchQuery) {
      const query = searchQuery.toLowerCase().trim();
      filtered = filtered.filter(country =>
        country.name.toLowerCase().includes(query) ||
        country.chineseName.toLowerCase().includes(query)
      );
    }
    if (activeTab !== '全部国家') {
      filtered = filtered.filter(country => country.continent === activeTab);
    }
    console.log('当前搜索词：', searchQuery);
    console.log('搜索结果：', filtered);
    this.setData({
      filteredCountries: filtered
    });
  },
  // 申请按钮点击事件
  onApplyClick() {
    wx.showToast({
      title: '申请成功！',
      icon: 'success',
      duration: 2000
    });
  },
  // 将 addCountry 方法移到这里，与其他方法同级
  addCountry(countryData) {
    wx.request({
      url: 'https://visa.goldenholiday.com/api/miniapp/admin/country/add',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        name: countryData.chineseName,
        name1: countryData.name,
        price: countryData.price,
        image: countryData.image,
        continent: countryData.continent
      },
      success: (res) => {
        if (res.data.code === 1) {
          wx.showToast({
            title: '添加成功',
            icon: 'success'
          });
          // 重新加载国家列表
          this.onLoad();
        } else {
          wx.showToast({
            title: '添加失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('添加国家失败：', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  // 切换下拉菜单显示状态
  toggleDropdown() {
    this.setData({
      isDropdownOpen: !this.data.isDropdownOpen
    });
  },

  // 修改标签切换处理
  handleTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab,
      isDropdownOpen: false  // 选择后关闭下拉菜单
    }, () => {
      this.filterCountries();
    });
  },

  // 页面滚动到底部时触发
  onReachBottom() {
    if (this.data.loading || !this.data.hasMore) return; // 防止重复加载和没有更多数据时加载

    this.setData({
      loading: true // 开始加载
    });

    // 模拟加载更多的操作
    setTimeout(() => {
      // 获取当前的国家列表
      const countriesToRepeat = this.data.filteredCountries;

      // 假设每次加载10个国家数据
      const nextCountries = this.data.countries.slice(countriesToRepeat.length, countriesToRepeat.length + 10);

      // 将加载的数据添加到已有数据中
      this.setData({
        filteredCountries: countriesToRepeat.concat(nextCountries)
      });

      // 判断是否已经显示了所有国家
      if (this.data.filteredCountries.length >= this.data.countries.length) {
        this.setData({
          loading: false,
          hasMore: false // 设置没有更多数据
        });
        wx.showToast({
          title: '已经到底部了',
          icon: 'none',
          duration: 2000
        });
      } else {
        this.setData({
          loading: false
        });
      }
    }, 1000);
  },
closeWangqinModal() {
  this.setData({
    showWangqinModal: false,
    wangqinLoading: false,
    wangqinResult: ''
  });
},
onWangqinDev() {
  this.setData({ wangqinLoading: true, wangqinResult: '' });
  setTimeout(() => {
    this.setData({ wangqinLoading: false, wangqinResult: '我就知道。' });
    setTimeout(() => {
      this.closeWangqinModal();
    }, 1200);
  }, 800);
},
onWangqinGod() {
  this.setData({ wangqinLoading: true, wangqinResult: '' });
  setTimeout(() => {
    this.setData({ wangqinLoading: false, wangqinResult: '神啊！我是您忠实而又诚恳的信徒！' });
    setTimeout(() => {
      this.closeWangqinModal();
    }, 1600);
  }, 800);
}
});
